package com.gzedu.module.controller.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gzedu.common.exception.MyException;
import com.gzedu.common.sys.controller.BaseController;
import com.gzedu.module.faced.meun.MeunFacade;
import com.gzedu.module.faced.user.UserFaced;
import com.gzedu.module.modle.meun.Meun;
import com.gzedu.module.modle.user.User;

@Controller
@RequestMapping("/login")
public class LoginController extends BaseController{
	
	@Autowired
	private UserFaced userFaced;
	@Autowired
	private MeunFacade meunFacade;
	
	@RequestMapping("/toLogin")
	public String toLogin(HttpServletRequest request,HttpServletResponse response){
		Subject currentUser = SecurityUtils.getSubject(); 
		if(currentUser.isAuthenticated()){
			return "redirect:/toIndex";
		}
		return "/views/login";
	}
	
	@RequestMapping("/login/auth")
	public String login(HttpServletRequest request,HttpServletResponse response,User user){
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword(), null); 
		Subject currentUser = SecurityUtils.getSubject(); 
		currentUser.login(token);  
		if(currentUser.isAuthenticated()){
			return "redirect:/login/toIndex";
		}else{
			return "redirect:/login/toLogin";
		}
		
	}
	
	@RequestMapping("/toIndex")
	public String toIndex(HttpServletRequest request,HttpServletResponse response,Model model) throws MyException{
		Subject currentUser = SecurityUtils.getSubject(); 
		User user = (User)currentUser.getSession().getAttribute("loginUser");
		if(user != null){
			Meun meun = meunFacade.getMeunByRole(user.getRoleCode());
			model.addAttribute("meun", meun);
		}else{
			return "redirect:/login/toLogin";
		}
		return "/views/index";
	}
}
